package com.chang.bootplus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chang.bootplus.base.exception.BusException;
import com.chang.bootplus.base.utils.ApiResponse;
import com.chang.bootplus.base.utils.BeanUtil;
import com.chang.bootplus.base.utils.FileUtils;
import com.chang.bootplus.controller.storage.local.LocalService;
import com.chang.bootplus.entity.News;
import com.chang.bootplus.mapper.NewsMapper;
import com.chang.bootplus.po.*;
import com.chang.bootplus.service.NewsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chang.bootplus.vo.NewsVO;
import lombok.RequiredArgsConstructor;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chang
 * @since 2022-01-23
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class NewsServiceImp extends ServiceImpl<NewsMapper, News> implements NewsService {

    final NewsMapper newsMapper;
    final LocalService localService;

    @Override
    public ApiResponse<NewsVO> listNews(NewsSelPO po) {
        List<News> news0 = newsMapper.listNews2(po);
        int count = news0.size();
        po.setPageNumber(po.getPageNumber()-1);
        List<News> news = newsMapper.listNews(po);

        if(news==null){
            throw new BusException("查询到的资讯为空");
        }

        Map<Boolean, List<News>> collect = news.stream().collect(Collectors.groupingBy(temp -> "置顶".equals(temp.getLabel())));
        List<News> newsTop = collect.get(true);
        List<News> newsOrdinary = collect.get(false);

        List<News> resList = new ArrayList<>();

        if(newsTop!=null && newsTop.size()!=0){
            List<News> collect1 = newsTop.stream().sorted(Comparator.comparing(News::getScore, Comparator.reverseOrder())
                    .thenComparing(News::getGmtCreate, Comparator.reverseOrder())).collect(Collectors.toList());

            collect1.stream().forEach(news1 -> resList.add(news1));
        }

        if(newsOrdinary!=null && newsOrdinary.size()!=0){
            List<News> collect2 = newsOrdinary.stream().sorted(Comparator.comparing(News::getScore, Comparator.reverseOrder())
                    .thenComparing(News::getGmtCreate, Comparator.reverseOrder())).collect(Collectors.toList());

            collect2.stream().forEach(news2 -> resList.add(news2));
        }

        List<NewsVO> newsVOS = BeanUtil.listA2ListB(resList,NewsVO.class);
        return new ApiResponse<>(newsVOS,new Long(newsVOS.size()),new Long(count));
    }

    /**
     * 转换content里面的图片src
     *
     * @param content  富文本的内容
     * @return
     */
    private String parseImage(String content) {
        Document doc = Jsoup.parseBodyFragment(content.toString().replaceAll("\r\n", ""));
        Elements pngs = doc.select("img");
        for (Element element : pngs) {
            //获得src
            String imgSrc = element.attr("src");
            //上传到临时目录，后面上传图片的时候直接从缓存目录取图片二次上传
            String tempDir = System.getProperty("user.dir") + "\\upimages\\temp\\";
            MultipartFile multipartFile = FileUtils.urlToMultipartFile(imgSrc, tempDir);
            //上传文件
            imgSrc = (String) localService.uploadFile(multipartFile, "dodoFUWENBEN").getBody().get("fileUrl");
//            ResultData resultData = upImageService.uploadImage(multipartFile);
//            UpImageDO upImageDO = (UpImageDO) resultData.getData();
//            networkUrlList.add(upImageDO.getNetworkUrl());
            //替换src
//            imgSrc = upImageDO.getNetworkUrl();
            element.attr("src", imgSrc);
        }
        //禁用文档的完美打印（避免多个空格被合成一个空格）
        doc.outputSettings(new Document.OutputSettings().prettyPrint(false));
        return doc.body().html();
    }


    @Override
    public ApiResponse<Void> addNews(NewsPO po) {
        News news = BeanUtil.beanA2beanB(po, News.class);
        boolean b = save(news);
        if(!b){
            throw new BusException("存储失败");
        }

        return new ApiResponse().setReMsg("存储成功");
    }

    @Override
    public ApiResponse<Void> deleteNews(NewsIdPO po) {
        boolean b = removeById(po.getId());
        if(!b){
            throw new BusException("删除失败");
        }

        return new ApiResponse().setReMsg("删除成功");
    }

    @Override
    public ApiResponse<Void> updateNews(NewsUpdatePO po) {
        News news = BeanUtil.beanA2beanB(po, News.class);
        boolean b = updateById(news);
        if(!b){
            throw new BusException("更新失败");
        }

        return new ApiResponse().setReMsg("更新成功");
    }

    @Override
    public ApiResponse<NewsVO> listBackNews(NewsSelBackPO po) {
        List<News> news0 = newsMapper.listBackNews2(po);
        int count = news0.size();
        po.setPageNumber(po.getPageNumber()-1);
        List<News> news = newsMapper.listBackNews(po);
        if(news==null){
            throw new BusException("查询到的资讯为空");
        }

        Map<Boolean, List<News>> collect = news.stream().collect(Collectors.groupingBy(temp -> "置顶".equals(temp.getLabel())));
        List<News> newsTop = collect.get(true);
        List<News> newsOrdinary = collect.get(false);

        List<News> resList = new ArrayList<>();

        if(newsTop!=null && newsTop.size()!=0){
            List<News> collect1 = newsTop.stream().sorted(Comparator.comparing(News::getScore, Comparator.reverseOrder())
                    .thenComparing(News::getGmtCreate, Comparator.reverseOrder())).collect(Collectors.toList());

            collect1.stream().forEach(news1 -> resList.add(news1));
        }

        if(newsOrdinary!=null && newsOrdinary.size()!=0){
            List<News> collect2 = newsOrdinary.stream().sorted(Comparator.comparing(News::getScore, Comparator.reverseOrder())
                    .thenComparing(News::getGmtCreate, Comparator.reverseOrder())).collect(Collectors.toList());

            collect2.stream().forEach(news2 -> resList.add(news2));
        }

        List<NewsVO> newsVOS = BeanUtil.listA2ListB(news, NewsVO.class);
        return new ApiResponse<>(newsVOS,new Long(newsVOS.size()),new Long(count));
    }


}
